package ltd.newbee.mall.util.paypal;

import com.paypal.core.PayPalHttpClient;
import com.paypal.http.HttpResponse;
import com.paypal.orders.*;
import lombok.Setter;
import ltd.newbee.mall.common.PaypalConstant;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.List;

/**
 * 订单创建
 * @author pyw
 */
@Setter
public class CreateOrder implements OrderAbstractHandler {

    private List<PurchaseUnitRequest> purchaseUnitRequest;

    @Value("${paypal.cancel.url}")
    private String paypalCancelUrl;
    @Value("${paypal.return.url}")
    private String paypalReturnUrl;


    @Override
    public OrderRequest buildRequestBody() {
        OrderRequest orderRequest = new OrderRequest();
        orderRequest.checkoutPaymentIntent(PaypalConstant.PaymentIntent.CAPTURE.name());
        ApplicationContext applicationContext = new ApplicationContext();
        applicationContext.brandName("testest").landingPage(PaypalConstant.LandingPage.NO_PREFERENCE.name())
                .cancelUrl(paypalCancelUrl)
                .returnUrl(paypalReturnUrl)
                .userAction(PaypalConstant.UserAction.CONTINUE.name())
                .shippingPreference(PaypalConstant.ShippingPreference.SET_PROVIDED_ADDRESS.name());
        orderRequest.applicationContext(applicationContext);
        orderRequest.purchaseUnits(purchaseUnitRequest);
        return orderRequest;
    }

    @Override
    public HttpResponse<Order> getResponseMessage(String id, PayPalHttpClient client) throws IOException {
        OrdersCreateRequest request = new OrdersCreateRequest();
        request.header("prefer","return=representation");
        request.requestBody(buildRequestBody());
        return client.execute(request);
    }
}
